package com.wswy.wzcx.ui.main.home;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.che.common.map.LocationModel;
import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.utils.CollectionUtils;
import com.che.libcommon.utils.RxHelper;
import com.che.libcommon.utils.ToastUtils;
import com.wswy.wzcx.api.ErrorCode;
import com.wswy.wzcx.jpush.PushChannel;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.ExtsKt;
import com.wswy.wzcx.model.ICity;
import com.wswy.wzcx.model.TabConfResp;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.model.WZCity;
import com.wswy.wzcx.model.core.EventNewsCategory;
import com.wswy.wzcx.model.core.EventTabConfResp;
import com.wswy.wzcx.model.home.ExtHomeMapper;
import com.wswy.wzcx.model.home.ExtModule;
import com.wswy.wzcx.model.home.LabelModel;
import com.wswy.wzcx.model.license.UserCarInfo;
import com.wswy.wzcx.model.news.NewsCategory;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.LocManager;
import com.wswy.wzcx.module.UserDataProvider;

import io.reactivex.Single;
import io.reactivex.observers.ResourceSingleObserver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

public class HomePresenter extends BaseHomePresenter {

    private static final String TAG = "HomePresenter";

    private static final String KEY_HOME_MODULE_CLICK = "home_module_";

    private Context context;
    private IHomeView homeView;


    public HomePresenter(Context context, IHomeView homeView) {
        this.context = context;
        this.homeView = homeView;

    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        loadMyCars(false);
        //loadCategories();
        //loadNewsCategory();
        //loadTopBanner();
        String city = LocManager.getInstance().getCurrentWZCity().name;
        homeView.showCity(city);
//    if (!TextUtils.isEmpty(city)){
//
//    }else {
//
//      LocationModel currentLocation = LocManager.getInstance().getCurrentLocation();
//      if (currentLocation != null) {
//        showCity(currentLocation);
//      }
//    }

        Single.fromCallable(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                GlobalConfigManager.getInstance().loadDevice();
                return null;
            }
        }).compose(RxHelper.io2main()).subscribe(new ResourceSingleObserver<Object>() {
            @Override
            public void onSuccess(Object o) {
            }

            @Override
            public void onError(Throwable e) {

            }
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadMyCars(true);
                PushChannel.getPushTagManager().updateTags();

            }
        }, 2000);


    }

    @Override
    protected boolean autoRegisterEvent() {
        return true;
    }

    @Override
    protected void onGetLocation(WZCity locationModel) {
        super.onGetLocation(locationModel);
        //如果没有选择城市
        if (TextUtils.isEmpty(locationModel.name)) {
            showCity(locationModel);
        }
        PushChannel.getPushTagManager().updateTags();
    }


    @Override
    protected void onUserCarInfoUpdate(@Nullable UserCarInfo userCarInfo) {
        super.onUserCarInfoUpdate(userCarInfo);
        homeView.updateCarInfo(userCarInfo);
    }

    @Override
    protected void onUserLoginSuccess(UserMode userMode) {
        super.onUserLoginSuccess(userMode);
        loadMyCars(true);
    }


    @Override
    protected void onDeleteCar(int carId) {
        super.onDeleteCar(carId);
        homeView.deleteCar(carId);
    }

    @Override
    protected void onLogout() {
        super.onLogout();
        homeView.showMyCars(null);
    }

    @Override
    protected void onMyCars(List<UserCarInfo> mycars) {
        super.onMyCars(mycars);
        homeView.showMyCars(mycars);
    }

    void changeCity(@NonNull ICity city) {
        //显示地址
        homeView.showCity(city.getCityName());
        //先隐藏天气信息
        homeView.showWeather(null);
        //保存
        if (city instanceof WZCity) {
            LocManager.getInstance().saveWZCity((WZCity) city);
        }
    }

    void loadMyCars(final boolean force) {

        if (DataCenter.get().hasLogin()) {
            UserDataProvider.get().myCars(force)
                    .subscribe(new ApiOptionalResultObserver<List<UserCarInfo>>() {
                        @Override
                        protected void onApiResult(@Nullable List<UserCarInfo> carInfos) {
                            onMyCars(carInfos);
                        }

                        @Override
                        protected void onApiError(BaseResult result) {

                            if (ErrorCode.isTokenInvalid(result)) {
                                homeView.showMyCars(null);
                            } else {
                                if (!force) {
                                    homeView.showMyCars(null);
                                }

                                homeView.setRefreshing(false);
                            }

                        }
                    });

        } else {
            homeView.showMyCars(null);
        }
    }

    void requestLocation() {
        LocManager.getInstance().lazyLoad();
    }


    private void showCity(WZCity locationModel) {
        homeView.showCity(locationModel.getCityName());
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventTabConfResp(EventTabConfResp resp) {
        TabConfResp tabConfResp = resp.getTabConfResp();
        List<ExtHomeMapper> list;
        if (tabConfResp != null && (list = tabConfResp.getHome()) != null) {
            Map<String, List<ExtModule>> convert = ExtsKt.convert(list);
            homeView.showCategory(convert);
        }
        list = null;
        //显示次级子模块
        if (tabConfResp != null && (list = tabConfResp.getHomeSecondary()) != null) {
            //Map<String, List<ExtModule>> convert = ExtsKt.convert(list);
            Map<LabelModel, List<ExtModule>> convert = new LinkedHashMap<>();
            Iterator<Entry<String, List<ExtModule>>> convertIterator = ExtsKt.convert(list).entrySet().iterator();
            while (convertIterator.hasNext()) {
                Entry<String, List<ExtModule>> next = convertIterator.next();
                List<ExtModule> modules = next.getValue();
                if (CollectionUtils.isEmpty(modules)) {
                    //忽略
                    convertIterator.remove();
                } else {
                    LabelModel labelModel = new LabelModel();
                    labelModel.title = next.getKey();
                    for (ExtModule module : modules) {
                        //如果有大图模式
                        if (module.getStyle() == 1) {
                            labelModel.style = 1;
                            break;
                        }
                    }
                    if (labelModel.style == 1 && modules.size() != 3) {
                        //大图模式 个数不正确 删除
                        convertIterator.remove();
                    } else {
                        convert.put(labelModel, modules);
                    }

                }
            }
            Iterator<Entry<LabelModel, List<ExtModule>>> iterator = convert.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<LabelModel, List<ExtModule>> entry = iterator.next();
                List<ExtModule> value = entry.getValue();
                //校验内容是否支持显示
                if (value == null || value.isEmpty()) {
                    iterator.remove();
                } else {
                    int size = value.size();
                    if (entry.getKey().style == 1) {
                        //左大又小的那种
                        entry.getKey().style = 1;
                        for (int i = 0; i < size; ) {
                            ExtModule extModule = value.get(i);
                            if (i + 2 < size) {
                                //第三个
                                ExtModule endModule = value.get(i + 2);
                                if (extModule.getStyle() + endModule.getStyle() == 1) {
                                    //只有一个是大图模式，正确 忽略中间值
                                    value.get(i + 1).weight = 0;
                                } else {
                                    //模式配置不对  删除
                                    iterator.remove();
                                    break;
                                }
                                i += 2;
                            } else {
                                break;
                            }
                        }
                    } else {
                        //全小
                        for (ExtModule extModule : value) {
                            extModule.weight = 0;
                        }
                    }
                }

            }
            homeView.showExtModules(convert);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventNewsCategory(EventNewsCategory event) {
        List<NewsCategory> news = event.getNews();
        if (news != null) {
            homeView.showNewsCategory(news);
//            homeView.showNewsCategory(null);
        }
    }

}
